import Web3 from "web3";
import masterContractAbi from "@/assets/json/ABI.json";
import { getInitDataApi } from "@/api/public";
import { defineStore } from "pinia";
import { store } from "../index";

export const useConfigStore = defineStore("configStore", {
  state: () => {
    return {
      loading: true,
      masterContract: null,
      masterContractAddress: "0x052B4b1510e7D3bA6c958a6f74Ab36BFB42d0FF7",
      usdtContract: null,
      usdtContractAddress: null,

      nftTotalContract: null,
      nftTotalContractAddress: null,

      dynamicTotalContract: null,
      dynamicTotalContractAddress: null,

      nftContractAddress: null,
      account: null,
      balance: 0,
      usdtBalance: 0,
      name: "",
      web3: null,
      globalData: {},
      referrerAddress: null
    };
  },
  getters: {
    getLoading(state) {
      return state.loading;
    },
    getAccount(state) {
      return state.account;
    },
    getEncryptAccount(state) {
      const account = state.account;
      return account?.replace(/^(.{4})(.*)(.{8})$/, "$1****$3");
    },
    getMasterContract(state) {
      return state.masterContract;
    },
    getWbe3(state) {
      return state.web3;
    },
    getYieldRate(state) {
      return Number(state.globalData.yield_rate ?? 0);
    }
  },
  actions: {
    async I_WEB3() {
      const { ethereum } = window;
      console.log("ethereum", ethereum);

      if (typeof ethereum === "undefined") {
        console.log("请确保已经安装任意钱包");
        return;
      }

      const web3 = new Web3(ethereum);
      console.log("web3工具");
      console.log(web3.utils);
      this.web3 = web3;

      ethereum.on("accountsChanged", accounts => {
        const [account] = accounts;
        this.SET_ACCOUNT(account);
        window.location.reload();
      });
    },
    async I_ACCOUNT() {
      if (this.web3 === null) {
        await this.I_WEB3();
      }

      const { ethereum } = window;

      try {
        const [account] = await ethereum.request({
          method: "eth_requestAccounts"
        });
        this.SET_ACCOUNT(account);
        await this.I_MASTER_CONTRACT();
        console.log("已连接账户: ", account);
      } catch (error) {
        console.error("账户连接请求被拒绝", error);
      } finally {
        this.loading = false;
      }
    },
    async I_MASTER_CONTRACT() {
      const _c = new this.web3.eth.Contract(
        masterContractAbi,
        this.masterContractAddress,
        {
          from: this.account
        }
      );
      this.masterContract = _c;

      await this.I_USDT_CONTRACT();

      const address = await this.masterContract.methods.nftAddr().call();
      this.nftContractAddress = address;

      this.GET_BALANCE(this.account);
      this.GET_REFERRER_ADDRESS();
      this.GET_NAME();
      this.GET_GLOBAL_DATA();

      this.I_NFT_TOTAL_CONTRACT();
      this.I_DYNAMIC_TOTAL_CONTRACT();
    },
    async I_USDT_CONTRACT() {
      // 从主合约中获取到usdt合约地址
      const address = await this.masterContract.methods.usdtAddr().call();
      this.usdtContractAddress = address;

      const _c = new this.web3.eth.Contract(
        masterContractAbi,
        this.usdtContractAddress,
        {
          from: this.account
        }
      );
      this.usdtContract = _c;
      this.GET_USDT_BALANCE(this.account);
    },
    async I_NFT_TOTAL_CONTRACT() {
      // NftTotal 合约
      const address = await this.masterContract.methods.nftTotalAdress().call();
      this.nftTotalContractAddress = address;

      const _c = new this.web3.eth.Contract(
        masterContractAbi,
        this.nftTotalContractAddress,
        {
          from: this.account
        }
      );
      this.nftTotalContract = _c;
    },
    async I_DYNAMIC_TOTAL_CONTRACT() {
      // dynamicTotal 合约
      const address = await this.masterContract.methods
        .dynamicTotalAdress()
        .call();
      this.dynamicTotalContractAddress = address;

      const _c = new this.web3.eth.Contract(
        masterContractAbi,
        this.dynamicTotalContractAddress,
        {
          from: this.account
        }
      );
      this.dynamicTotalContract = _c;
    },
    async GET_BALANCE(account) {
      if (!account) return;
      const wei = await this.getMasterContract.methods
        .balanceOf(account)
        .call();
      const ether = this.web3.utils.fromWei(wei, "ether");
      this.balance = parseFloat(ether);
    },
    async GET_USDT_BALANCE(account) {
      if (!account) return;
      const wei = await this.usdtContract.methods.balanceOf(account).call();
      const ether = this.web3.utils.fromWei(wei, "ether");
      this.usdtBalance = parseFloat(ether);
    },
    async GET_NAME() {
      const name = await this.getMasterContract.methods.name().call();
      this.name = name;
    },
    async GET_REFERRER_ADDRESS() {
      const _referrerAddress = await this.getMasterContract.methods
        .getInvitationRelationship(this.account)
        .call();
      this.referrerAddress =
        _referrerAddress != "0x0000000000000000000000000000000000000000"
          ? _referrerAddress
          : null;
    },

    SET_ACCOUNT(val) {
      this.account = val;
    },
    // 获取中心化配置
    async GET_GLOBAL_DATA() {
      const res = await getInitDataApi();
      this.globalData = res;
    },
    async ALLOWANCE_USDT() {
      // 查询在usdt向主合约的授权额度
      const res = await this.masterContract.methods
        .getTokenAllowance(this.usdtContractAddress, this.account)
        .call();
      const n = this.web3.utils.fromWei(res, "ether");
      const amount = Number(n);
      console.log("USDT已授权数量", amount);
      return amount;
    }
  }
});

export const useConfigStoreWithOut = () => {
  return useConfigStore(store);
};
